package top.jimc.ehcache.service.impl;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import top.jimc.ehcache.po.User;
import top.jimc.ehcache.service.EhcacheService;

/**
 * @author Jimc.
 * @since 2018/9/21.
 */
@Service
public class EhcacheServiceImpl implements EhcacheService {

    @Cacheable(value = "cacheTest", key = "#param")
    public String getTimestamp(String param) {
        return String.valueOf(System.currentTimeMillis());
    }

    @Cacheable(value = "cacheTest", key = "#key")
    public String getDataFromDB(String key) {
        System.out.println("模拟从数据库中获取数据...");
        return key + ":" + String.valueOf(Math.round(Math.random()*1000000));
    }

    @CacheEvict(value = "cacheTest", key = "#key")
    public void removeDataAtDB(String key) {
        System.out.println("模拟从数据库中删除数据...");
    }

    @CachePut(value = "cacheTest", key = "#key")
    public String refreshData(String key) {
        System.out.println("模拟从数据库中加载数据...");
        return key + "::" + String.valueOf(Math.round(Math.random()*1000000));
    }



    @Cacheable(value = "cacheTest", key = "'user:' + #userId")
    public User findUserById(String userId) {
        System.out.println("模拟从数据库中查询数据");
        return new User(userId, "Tom");
    }

    /**
     * 清除cacheTest中指定key的缓存
     */
    @CacheEvict(value = "cacheTest", key = "'user:' + #userId")
    public void removeUserById(String userId) {
        System.out.println("cacheTest remove:" + userId);
    }

    /**
     * 清除cacheTest中全部缓存
     */
    @CacheEvict(value = "cacheTest", allEntries = true)
    public void removeAllUser() {
        System.out.println("cacheTest remove all");
    }
}
